<?php

namespace app\manystore\controller\shopro;

use app\common\controller\Backend;
use app\common\controller\ManystoreBase;
use think\Db;

/**
 * 商品
 *
 * @icon fa fa-circle-o
 */
class Goods extends ManystoreBase
{

    /**
     * Goods模型对象
     * @var \app\admin\model\shopro\Goods
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\manystore\model\shopro\Goods;
        $this->view->assign("typeList", $this->model->getTypeList());
        $this->view->assign("statusList", $this->model->getStatusList());
        $this->view->assign("isIndexList", $this->model->getIsIndexList());
        $this->view->assign("dispatchTypeList", $this->model->getDispatchTypeList());
        $this->view->assign("store_id", MANY_STORE_ID);
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = false;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildstoreparams('title');
            $total = $this->model
                ->where($where)
                ->order($sort, $order)
                ->count();

            $list = $this->model
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            foreach ($list as $row) {
                $row->visible(['id', 'type', 'title', 'status', 'weigh', 'category_ids', 'image', 'price', 'likes', 'views', 'sales', 'dispatch_type', 'updatetime']);

            }
            $list = collection($list)->toArray();
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            $sku = $this->request->post("sku/a");

            if ($params) {
                $params = $this->preExcludeFields($params);

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                $result = false;
                Db::startTrans();
                try {
                    $result = $this->model->validate('\app\admin\validate\shopro\Goods.add')->allowField(true)->save($params);
                    if (!$result) {
                        $this->error($this->model->getError());
                    }
                    $this->editSku($this->model, $sku);


                    Db::commit();

                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $row->updatetime = time();

        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            $sku = $this->request->post("sku/a");

            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    $result = $row->validate('\app\admin\validate\shopro\Goods.edit')->allowField(true)->save($params);
                    if (!$result) {
                        $this->error($row->getError());
                    } else {
                        $this->editSku($row, $sku);
                        Db::commit();
                    }
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        $skuList = \app\admin\model\shopro\GoodsSku::all(['pid' => 0, 'goods_id' => $ids]);
        if ($skuList) {
            foreach ($skuList as &$s) {
                $s->children = \app\admin\model\shopro\GoodsSku::all(['pid' => $s->id, 'goods_id' => $ids]);
            }
        }
        $this->assignconfig('skuList', $skuList);
        $skuPrice = \app\admin\model\shopro\GoodsSkuPrice::all(['goods_id' => $ids]);
        $this->assignconfig('skuPrice', $skuPrice);
        return $this->view->fetch();
    }

    public function select()
    {
        if ($this->request->isAjax()) {
            return $this->index();
        }
        return $this->view->fetch();
    }

    protected function editSku($goods, $sku)
    {
        $skuList = json_decode($sku['listData'], true);
        $skuPrice = json_decode($sku['priceData'], true);
        if (count($skuList) < 1) {
            $this->error('请填写规格列表');
        }
        if (count($skuPrice) < 1) {
            $this->error('请填写规格价格');
        }


        foreach ($skuPrice as &$price) {
            if (empty($price['price']) || $price['price'] == 0) {
                $this->error('请填写规格价格');
            }
            if ($price['stock'] === '') {
                $this->error('请填写规格库存');
            }
            if (empty($price['weight'])) {
                $price['weight'] = 0;
            }
        }

        $goodsSku = \app\admin\model\shopro\GoodsSku::get(['goods_id' => $goods->id]);
        $allChildrenSku = [];
        if (!$goodsSku) { //创建新产品，添加规格列表和规格价格
            foreach ($skuList as $s1 => &$k1) {
                //添加主规格
                $skuId[$s1] = \app\admin\model\shopro\GoodsSku::insertGetId([
                    'name' => $k1['name'],
                    'pid' => 0,
                    'goods_id' => $goods->id
                ]);
                $k1['id'] = $skuId[$s1];
                foreach ($k1['children'] as $s2 => &$k2) {
                    $skuChildrenId[$s1][$s2] = \app\admin\model\shopro\GoodsSku::insertGetId([
                        'name' => $k2['name'],
                        'pid' => $k1['id'],
                        'goods_id' => $goods->id
                    ]);
                    $allChildrenSku[$k2['id']] = $skuChildrenId[$s1][$s2];
                    $k2['id'] = $skuChildrenId[$s1][$s2];
                    $k2['pid'] = $k1['id'];
                }
            }

            foreach ($skuPrice as $s3 => &$k3) {

                unset($k3['id']);
                $k3['goods_sku_ids'] = $this->checkRealIds($k3['goods_sku_ids'], $allChildrenSku);
                $k3['goods_id'] = $goods->id;
                $k3['goods_sku_text'] = implode(',', $k3['goods_sku_text']);
                $k3['weight'] = intval($k3['weight']);
            }
            $res = \app\admin\model\shopro\GoodsSkuPrice::insertAll($skuPrice);


        } else {
            //只更新规格价格
            $goodsSkuPrice = new \app\manystore\model\shopro\GoodsSkuPrice;
            $goodsSkuPrice->saveAll($skuPrice);

        }
    }

    private function checkRealIds($newGoodsSkuIds, $allChildrenSku)
    {
        $idsArray = explode(',', $newGoodsSkuIds);
        $newIdsArray = [];
        foreach ($idsArray as $id) {
            $newIdsArray[] = $allChildrenSku[$id];
        }
        return implode(',', $newIdsArray);

    }
}
